import urllib.request
from lxml import etree


def create_request(page1):
    """
    创建请求对象
    :return: request
    """
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/123.0.0.0'
                      'Safari/537.36'
    }
    base_url = 'https://sc.chinaz.com/tupian/ribenmeinv'
    if page1:
        return urllib.request.Request(url=base_url+".html", headers=headers)
    else:
        return urllib.request.Request(url=base_url+str(page1)+".html", headers=headers)


def get_content(request1):
    """
    获取网页数据
    :param request1: 请求
    :return: 网页数据
    """
    response = urllib.request.urlopen(request1)
    return response.read().decode('utf-8')


def parse_content(content1):
    """
    解析网站内容获取要下载的图片地址
    :param content1: 网页内容
    :return: 要下载的图片字典 key 文件名  val 图片地址
    """
    alt_src = {}
    tree = etree.HTML(content1)
    # 一般设计网站的图片都会懒加载.
    srcs = tree.xpath('//img[@class="lazy"]/@data-original')
    alt = tree.xpath('//img[@class="lazy"]/@alt')
    for i in range(len(srcs)):
        print(srcs[i], alt[i])
        alt_src.setdefault(srcs[i], alt[i])
    return alt_src


def down_load_image(images1):
    """
    下载对应的图片
    :param images1: 要下载的图片字典 key 文件名  val 图片地址
    :return: None
    """
    for key, value in images1.items():
        print(key, value)
        urllib.request.urlretrieve(url="https:" + key, filename="./images/"+value+'.jpg')


if __name__ == '__main__':
    start_page = int(input('请输入要下载照片的起始页:'))
    end_page = int(input('请输入要下载照片的终止页:'))
    for page in range(start_page, end_page+1):
        # 创建请求对象
        request = create_request(page)
        # 请求文件
        content = get_content(request)
        # 解析网站
        images = parse_content(content)
        # 下载图片
        down_load_image(images)
